package cn.com.nes.common.util.listener;

import cn.com.nes.common.util.MathUtils;
import cn.hutool.core.math.MathUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.UUID;

public class IdUtil {
    private static String middle = "";

    static {
        try {
            middle = fillOrSub(
                    //4位IP地址hash
                    Math.abs(InetAddress.getLocalHost().getHostAddress().hashCode()) + "", 4, '0') +
                    //4位PID进程hash
                    fillOrSub(ManagementFactory.getRuntimeMXBean().getName().split("@")[0], 4, '0');
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 以毫微秒做基础计数, 返回唯一有序增长ID
     * <pre>System.nanoTime()</pre>
     * <pre>
     * 	线程数量: 	100
     * 	执行次数: 	1000
     * 	平均耗时: 	222 ms
     * 	数组长度: 	100000
     * 	Map Size: 	100000
     * </pre>
     *
     * @return ID长度32位
     */
    public static String getIncreaseIdByNanoTime() {
        return
                //时间戳-14位
                System.nanoTime() +
                        //标志-8位
                        middle +
                        fillOrSub(
                                //3位线程标志
                                Thread.currentThread().hashCode() + "", 3, '0') +
                        //随机7位数
                        RandomUtil.randomInt(1000000, 9999999);
    }

    private static String fillOrSub(String target, int len, char filledChar) {
        return target.length() < len
                ? StrUtil.fillAfter(target, filledChar, len)
                : target.substring(0, len);
    }

    public static void main(String[] args) {
        System.out.println(IdUtil.getIncreaseIdByNanoTime());
    }

}
